<?php

namespace app\controller;

use support\Redis;
use support\Request;
use think\facade\Db;
use Illuminate\Support\Env;
use app\controller\RestBase;
use PhpAmqpLib\Wire\AMQPTable;
use App\validate\BoxOrderValidate;
use PhpAmqpLib\Message\AMQPMessage;
use crmeb\exceptions\AdminException;
use think\exception\ValidateException;
use App\service\order\BoxOrderServices;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

class BoxOrderApi
{
    /**
     * 统一下单 购买盲盒
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function create(Request $request)
    {
        $token = $request->header('XX-Token');
        $deviceType = $request->header('XX-Device-Type');

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'wxapp', 'ios'];

        if (empty($token)) {
            return json(['code' => 0, 'msg' => '请传入XX-Token']);
        }

        if (empty($deviceType)) {
            return json(['code' => 0, 'msg' => '请传入XX-Device-Type']);
        }

        if (!in_array($deviceType, $allowedDeviceTypes)) {
            return json(['code' => 0, 'msg' => '设备类型错误']);
        }

        $user = Db::name('user_token')
            ->where('token', $token)
            ->where('device_type', $deviceType)
            ->find();

        if (!$user) {
            return json(['code' => 0, 'msg' => '请先登录', 'user' => $user]);
        }

        $userId = $user['user_id'];

        $data = [
            'uid' => $userId,
            'box_id' => $request->post('box_id') ?? '', // 盲盒id
            'pay_type' => $request->post('pay_type') ?? '', // 支付方式 sd_h5_checkstand 杉德H5收银台支付  hf 汇付支付
            'buy_count' => $request->post('buy_count') ?? 1, // 购买数量
            'order_pk_id' => $request->post('order_pk_id') ?? 0, // 订单主键id 重新付款的时候 传入
        ];

        $validate = new BoxOrderValidate;

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $boxOrderServices = new BoxOrderServices();

        $expire = 10; // 有效期 10秒
        $key = $userId . ':lock'; // key
        $value = time() + $expire; // 锁的值 = unix 时间戳 + 锁的有效期

        $lock = Redis::setNx($key, $value); // 只能是一个线程 会 变为 true

        if (empty($lock)) {
            return json(['code' => 0, 'msg' => '正在执行中......']);
        } else {
            try {
                $res = $boxOrderServices->boxOrderCreate((int)$userId, (int)$data['box_id'], (int)$data['buy_count'], $data['pay_type'], (int)$data['order_pk_id']);
            } catch (AdminException $e) {
                Redis::del($key);
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            Redis::del($key);
        }

        return json(['code' => 1, 'msg' => '提交H5盲盒支付成功', 'data' => $res]);
    }

    /**
     * 购买盲盒
     * 杉德支付成功通知
     * @param Request $request
     * @return string|\support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payNotify(Request $request)
    {
        $data = $request->post();
        $boxOrderServices = new BoxOrderServices();
        try {
            $boxOrderServices->boxPayNotifyNew($data);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return '{respCode=000000}';
    }

    // 统一下单 购买盲盒 压力测试
    public function test(Request $request)
    {
        $userId = 314753846876442625;

        $data = [
            'uid' => $userId,
            'box_id' => $request->get('box_id') ?? '', // 盲盒id
            'pay_type' => $request->get('pay_type') ?? '', // 支付方式 sd_h5_checkstand 杉德H5收银台支付  hf 汇付支付
            'buy_count' => $request->get('buy_count') ?? 1, // 购买数量
            'order_pk_id' => $request->get('order_pk_id') ?? 0, // 订单主键id 重新付款的时候 传入
        ];

        $validate = new BoxOrderValidate;

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $boxOrderServices = new BoxOrderServices();

        try {
            $res = $boxOrderServices->boxOrderCreateTest($userId, (int)$data['box_id'], (int)$data['buy_count'], $data['pay_type'], (int)$data['order_pk_id']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '压力测试提交H5盲盒支付成功！', 'data' => $res]);
    }


    public function index(Request $request)
    {
        return response(__CLASS__);
    }

}
